package com.haoqizhe.kernel.entity;

import com.haoqizhe.kernel.commons.constants.HeaderConstants;
import com.haoqizhe.kernel.commons.enums.ResultCode;
import com.haoqizhe.kernel.web.result.DefaultErrorResult;
import com.haoqizhe.kernel.commons.util.IpUtil;
import com.haoqizhe.kernel.core.entity.UserEntity;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.http.HttpStatus;

import javax.servlet.http.HttpServletRequest;
import java.io.Serializable;

/**
 *  日志信息
 * @author haoqizhe.li
 * @date 2018/4/10 17:40
 */
@Data
@NoArgsConstructor
@AllArgsConstructor
public class LogEntity implements Serializable{

    /**
     * 请求者IP
     */
    private String requestIp;
    /**
     * 服务器IP
     */
    private String serverIp;
    /**
     * 请求方法名称
     */
    private String methodName;
    /**
     * 请求参数
     */
    private String params;

    /**
     * 请求者（登陆用户）
     */
    private String requester;

    /**
     * 调用来源 PC  安卓  IOS...
     */
    private String callSource;

    /**
     * APP版本
     */
    private String appVersion;

    /**
     * 接口文档版本
     */
    private String apiVersion;

    /**
     * 请求 user-agent
     */
    private String userAgent;

    /**
     * 响应消息
     */
    private String response;

    /**
     * 请求耗时
     */
    private Long cost;

    /**
     * 异常信息
     */
    private DefaultErrorResult errorResult;

    /**
    * 获取请求日志信息
    * @return 请求日志信息
    * @author haoqizhe.li
    * @date 2018/4/10 21:08
    **/
    public static LogEntity getLogEntity(Exception e, HttpServletRequest request, UserEntity loginUser){

        LogEntity  logEntity = new LogEntity();

        logEntity.setRequestIp(IpUtil.getRealIp(request));
        logEntity.setServerIp(IpUtil.getServiceIp());
        logEntity.setRequester(loginUser == null ? "unknown" : String.valueOf(loginUser.getUserAccount()));
        logEntity.setCallSource(request.getHeader(HeaderConstants.CALL_SOURCE));
        logEntity.setAppVersion(request.getHeader(HeaderConstants.APP_VERSION));
        logEntity.setApiVersion(request.getHeader(HeaderConstants.API_VERSION));
        logEntity.setUserAgent(request.getHeader("user-agent"));

        if(e != null){
            logEntity.setErrorResult(DefaultErrorResult.failure(ResultCode.SYSTEM_INNER_ERROR,e, HttpStatus.INTERNAL_SERVER_ERROR));
        }
        return logEntity;
    }

}
